package com.jsle.financial.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.jsle.financial.domain.Company;
import com.jsle.financial.domain.Company_Resources;
import com.jsle.financial.service.CompanyService;
import com.jsle.financial.util.AJAXUtil;
import com.jsle.financial.util.Constants;
import com.jsle.financial.util.Tools;
import com.jsle.financial.vo.Page;
import com.jsle.financial.vo.Result;

/**
 * 公司管理Controller
 * @author wisdying
 * @date 2012-10-26
 */
@Controller
@RequestMapping("/company")
public class CompangyController {
	private Log log = LogFactory.getLog(CompangyController.class);
	@Resource
	private CompanyService companyService;
	

	/**
	 * 分页查询公司
	 * @param list
	 * @param model
	 * @return
	 */
//	@RequestMapping(value = "/selCompanys.do",produces = "application/json")
//	@ResponseBody
//	public void selCompanys(HttpServletRequest request,HttpServletResponse response){
//		AJAXUtil.setCharacterEncoding(request,response);
//		int pageSize = Integer.valueOf(WebUtils.findParameterValue(request, "pageSize"));
//		int pageNo = Integer.valueOf(WebUtils.findParameterValue(request, "pageNo"));
//		String companyName = WebUtils.findParameterValue(request, "companyName");
//		pageNo = (pageNo==0?0:(pageNo*pageSize+1));
//		Page page = new Page(pageNo,pageSize);
//		System.out.println(pageNo+"||");
//		Result result = companyService.queryCompanysByPage(page, companyName);
//		String sb = "";
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Page pageResult = new Page();
//		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
//			pageResult = (Page)result.getResultValue();
//			List<Company> cps = new ArrayList<Company>();
//			if(pageResult.getData()!=null){
//				cps = pageResult.getData();
//			}
//			sb = ControllerHelper.getCompanysDataJsonByList(cps);
//		}
//		
//		String json = "{success:true,pageNo:" + pageNo + ",totalPageCount:"
//		+ pageResult.getPageCount() + ",totalcount:"+pageResult.getTotalCount()+", data:[" + sb.toString()
//		+ "]}";
//		System.out.println("json#####"+json);
////		User user = new User("zhangyq","123","张艳青","员工",new Date(),new Date(),1);
//		AJAXUtil.writerJson(response,json);
//	}
	/**
	 * 新增公司
	 */
	@RequestMapping(value = "/addCompany.do",method=RequestMethod.POST)
	@ResponseBody
	public void addCompany(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String companyCode = WebUtils.findParameterValue(request, "companyCode");
		String companyName = WebUtils.findParameterValue(request, "companyName");
		Company company = new Company();
		company.setCompanyCode(companyCode);
		company.setCompanyName(companyName);
		Result rs = companyService.addCompany(company);
		
		if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
		}else{
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
		}
	}
	/**
	 * 删除单个公司
	 */
	@RequestMapping(value = "/delCompany.do",method=RequestMethod.POST)
	@ResponseBody
	public void delCompany(Company company,HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String id = request.getParameter("id");
		company.setId(new Integer(id));
		Result rs = new Result();
		rs = companyService.delUsersByCompany(company);//删人
		rs = companyService.delUserUserGroupsByCompany(company);//删除人员用户组关系
		rs = companyService.delUserGroupsByCompany(company);//删用户组
		rs = companyService.delCompanyResourcesByCompany(company);//删公司配置的资源关联
		rs = companyService.delCompany(company);//删公司
		if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
		}else{
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
		}
	}
	
	/**
	 * 分页查询公司
	 * @param list
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/selCompanys.do",produces = "application/json")
	@ResponseBody
	public void selCompanys(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		int pageSize = Integer.valueOf(WebUtils.findParameterValue(request, "pageSize"));
		int pageNo = Integer.valueOf(WebUtils.findParameterValue(request, "pageNo"));
		String companyName = WebUtils.findParameterValue(request, "companyName");
		pageNo = (pageNo==0?0:(pageNo*pageSize+1));
		Page page = new Page(pageNo,pageSize);
		Result result = companyService.queryCompanysByPage(page, companyName);
		String sb = "";
		Page pageResult = new Page();
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			pageResult = (Page)result.getResultValue();
			List<Company> cps = new ArrayList<Company>();
			if(pageResult.getData()!=null){
				cps = pageResult.getData();
			}
			sb = ControllerHelper.getCompanysDataJsonByList(cps);
		}
		
		String json = "{success:true,pageNo:" + pageNo + ",totalPageCount:"
		+ pageResult.getPageCount() + ",totalcount:"+pageResult.getTotalCount()+", data:[" + sb.toString()
		+ "]}";
		System.out.println("json#####"+json);
		AJAXUtil.writerJson(response,json);
	}
	
	/**
	 * 修改公司信息
	 * @param list
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/updateCompany.do",method=RequestMethod.POST)
	@ResponseBody
	public void updateCompany(Company company,HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String resids = request.getParameter("resourceids");
		List<Integer> rids = new ArrayList<Integer>();
		if(null!=resids && "" !=resids){
			for (String id  : resids.split(",")) {
				rids.add(new Integer(id));
			}
		}
		List<Company_Resources> crs = getListCompanyResourcesByIds(company.getId(), rids);
		company.setCrs(crs);
		Result rs = new Result();
//		rs = companyService.delUsersByCompany(company);//删人
//		rs = companyService.delUserUserGroupsByCompany(company);//删除人员用户组关系
//		rs = companyService.delUserGroupsByCompany(company);//删用户组
		rs = companyService.delCompanyResourcesByCompany(company);//删公司配置的资源关联
		rs = companyService.updateCompany(company);
		if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
		}else{
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
		}
	}
	
	@RequestMapping(value = "/initUpdateCompany.do",method=RequestMethod.POST)
	@ResponseBody
	public void initUpdateCompany(Company company,HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String id = request.getParameter("id");
		if(null != id){
			company.setId(Integer.valueOf(id));
		}
		Result rs = companyService.queryCompanyByCompanyID(company);
		Company cm = (Company)rs.getResultValue();
		List<Company_Resources> crs = new ArrayList<Company_Resources>();
		rs = companyService.getCompanyRes(cm);
		if(rs.getResultValue() != null){
			crs = (List<Company_Resources>)rs.getResultValue();
			cm.setCrs(crs);
		}
		
		//rs.setResultValue(cm);
		String sb = ControllerHelper.getCompanysResDataJsonByList(cm);
		AJAXUtil.writerJson(response, sb);
	}
	@RequestMapping(value = "/selCompanyCombo.do",method=RequestMethod.POST)
	@ResponseBody
	public void selCompanyCombo(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		List<Company> ret = new ArrayList<Company>();
		Result rs = companyService.queryCompanys();
		if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			ret = (List<Company>)rs.getResultValue();
		}
		String sb = ControllerHelper.getCompanysDataJsonByList(ret);
		String json = "{success:true" +", data:[" + sb + "]}";
		AJAXUtil.writerJson(response, json);
	}
	
	/**
	 * 配置公司资源
	 * @param list
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/addCompanyResources.do",method=RequestMethod.POST)
	@ResponseBody
	public void addCompanyResources(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		int companyId = Integer.valueOf(WebUtils.findParameterValue(request, "companyId"));
		String resourceIdStr =  WebUtils.findParameterValue(request, "resourceIdStr");
		
		String [] resourceIdStrArrs = resourceIdStr.split(",");//页面传入的资源id字符串切割获取资源id字符数组
		Result rs = new Result();
		if(resourceIdStr!=null){
			//资源id字符数组封装成资源id整型集合
			List<Integer> resourceIds = new ArrayList<Integer>();
			for(String id : resourceIdStrArrs){
				resourceIds.add(Integer.valueOf(id));
			}
			//循环添加公司配置资源
			List<Company_Resources> list = getListCompanyResourcesByIds(companyId,resourceIds);
			for(Company_Resources cr : list){
				rs = companyService.addCompanyAndResources(cr);
			}
			
			if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
				AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
			}else{
				AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
			}
		}else{
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
		}
		
	}
	
	/**
	 * 通过公司及配置的资源id封装，返回公司配置的资源对象集合
	 * @param companyId
	 * @param resourceIds
	 * @return
	 */
	private List<Company_Resources> getListCompanyResourcesByIds(int companyId, List<Integer> resourceIds){
		List<Company_Resources> list= new ArrayList<Company_Resources>();
		for(Integer resourceId : resourceIds){
			Company_Resources cr = new Company_Resources();
			cr.setCompanyId(companyId);
			cr.setResourceId(resourceId);
			list.add(cr);
		}
		return list;
	}
	
	@RequestMapping(value = "/newCode.do",method=RequestMethod.POST)
	@ResponseBody
	public void newCode(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String code = WebUtils.findParameterValue(request, "code");
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		code += sdf.format(date);
		String sb = "{\"success\":true,\"code\":\""+code+"\"}";
		AJAXUtil.writerJson(response, sb);
	}

}
